package com.wwwzh.himalayafm.adapter.recommend;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.wwwzh.himalayafm.BR;
import com.wwwzh.himalayafm.R;
import com.wwwzh.himalayafm.callback.OnImageClickListener;
import com.wwwzh.himalayafm.callback.OnRecommDestroyListener;
import com.wwwzh.himalayafm.entity.AdEntity;
import com.wwwzh.himalayafm.entity.recommend.RecommFousImage;
import com.wwwzh.himalayafm.entity.recommend.RecommendDisItem;
import com.wwwzh.himalayafm.entity.recommend.RecommendDiscovery;
import com.wwwzh.himalayafm.entity.recommend.RecommendEntityOne;
import com.wwwzh.himalayafm.entity.recommend.RecommendGuessItem;
import com.wwwzh.himalayafm.entity.recommend.RecommendItem;
import com.wwwzh.himalayafm.retrofit.HttpService;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by weizz on 2016/12/5.
 */

public class RecommendAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnRecommDestroyListener {


    public static final int ITEM_TYPE_HEADER = 0;
    public static final int ITEM_TYPE_CONTENT = 1;
    public static final int ITEM_TYPE_DISCOVERY = 2;
    public static final int ITEM_TYPE_GUESS = 3;
    public static final int ITEM_TYPE_SPECIAL = 4;
    public static final int ITEM_TYPE_BOTTOMAD = 5;

    private Context context;
    private LayoutInflater inflater;
    private List<RecommendItem> lists;
    private int variableId;
    //焦点图集合
    private List<RecommFousImage> mlist;
    private List<AdEntity.AdContent> adList;
    private List<RecommendGuessItem> gList;
    private static OnImageClickListener mlistener;
    private RecommendEntityOne entityOne;
    private int curPosition = 0;
    private int adCurPosition = 0;
    private Timer timer;
    private Timer timer2;
    private boolean isFirst = false;

    public RecommendAdapter(Context context, List<RecommendItem> list, List<RecommendGuessItem> glist, RecommendEntityOne entityone, int variableId) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.lists = list;
        this.gList = glist;
        this.variableId = variableId;
        mlist = new ArrayList<>();
        isFirst = true;
        this.entityOne = entityone;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_HEADER) {
            return new HeaderViewHolder(inflater.inflate(R.layout.layout_recomm_header, parent, false));
        } else if (viewType == ITEM_TYPE_DISCOVERY) {
            return new DiscoveryViewHolder(inflater.inflate(R.layout.layout_recomm_discovery, parent, false));
        } else if (viewType == ITEM_TYPE_GUESS) {
            return new GuessViewHolder(inflater.inflate(R.layout.layout_recomm_guess, parent, false));
        } else if (viewType == ITEM_TYPE_SPECIAL) {
            return new SpecialViewHolder(DataBindingUtil.inflate(inflater, R.layout.layout_recomm_special, parent, false));
        } else if (viewType == ITEM_TYPE_BOTTOMAD) {
            return new BottomAdViewHolder(inflater.inflate(R.layout.layout_recomm_bottomad, parent, false));
        } else {
            ViewDataBinding binding = DataBindingUtil.inflate(inflater, R.layout.layout_recomm_item, parent, false);
            return new ContentViewHolder(binding);
        }
    }


    //绑定viewHolder
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderViewHolder) {
            initViewPager((HeaderViewHolder) holder);
        } else if (holder instanceof DiscoveryViewHolder) {
            initRecommDiscovery((DiscoveryViewHolder) holder);
        } else if (holder instanceof GuessViewHolder) {
            initeGuessItem((GuessViewHolder) holder);
        } else if (holder instanceof ContentViewHolder && position == 3) {
            ((ContentViewHolder) holder).binding.setVariable(variableId, entityOne.getEditorRecommendAlbums());
            ((ContentViewHolder) holder).image1.setOnClickListener(new ClickListener("1"));
            ((ContentViewHolder) holder).image2.setOnClickListener(new ClickListener("2"));
            ((ContentViewHolder) holder).image3.setOnClickListener(new ClickListener("3"));
        } else if (holder instanceof SpecialViewHolder) {
            initSpecialItem((SpecialViewHolder) holder);
        } else if (holder instanceof BottomAdViewHolder) {
            initBottomAd((BottomAdViewHolder) holder);
        } else if (holder instanceof ContentViewHolder) {
            ((ContentViewHolder) holder).binding.setVariable(variableId, lists.get(position - 5));
            ((ContentViewHolder) holder).image1.setOnClickListener(new ClickListener(lists.get(position-5).getList().get(0).getAlbumId()));
            ((ContentViewHolder) holder).image2.setOnClickListener(new ClickListener(lists.get(position-5).getList().get(1).getAlbumId()));
            ((ContentViewHolder) holder).image3.setOnClickListener(new ClickListener(lists.get(position-5).getList().get(2).getAlbumId()));
        }
    }

    //底部广告
    private void initBottomAd(final BottomAdViewHolder holder) {
        adList = new ArrayList<AdEntity.AdContent>();
        HttpService.BottomAdGetService service = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.BottomAdGetService.class);
        service.getBottomAd().enqueue(new Callback<AdEntity>() {
            @Override
            public void onResponse(Call<AdEntity> call, Response<AdEntity> response) {
                adList.addAll(response.body().getData());
                AdImageAdapter adAdapter = new AdImageAdapter(adList, context);
                holder.adViewPager.setAdapter(adAdapter);
                adAutoCycle(holder);
                holder.adViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        adCurPosition = position;
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }

            @Override
            public void onFailure(Call<AdEntity> call, Throwable t) {

            }
        });


    }

    //精品听单
    private void initSpecialItem(SpecialViewHolder holder) {
        holder.specialBinding.setVariable(BR.special, entityOne.getSpecialColumn().getList().get(0));
        holder.specialLayout.setOnClickListener(new ClickListener("special"));
    }

    //猜你喜欢条目
    private void initeGuessItem(GuessViewHolder holder) {

        GuessItemAdapter guessAdapter = new GuessItemAdapter(context, gList);
        holder.gridView.setLayoutManager(new GridLayoutManager(context, 3));
        holder.gridView.setAdapter(guessAdapter);
    }

    //推荐界面第二个viewpager
    private void initRecommDiscovery(final DiscoveryViewHolder holder) {
        RecommendDiscovery discoveryEntity2 = new RecommendDiscovery();
        RecommendDiscovery discoveryEntity = entityOne.getDiscoveryColumns();
        List<View> views = new ArrayList<>();
//        List<RecommendDiscovery> entityList = new ArrayList<>();
//        entityList.add(discoveryEntity);
        List<RecommendDisItem> halfList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            halfList.add(entityOne.getDiscoveryColumns().getList().get(i + 4));
        }
        discoveryEntity2.setList(halfList);
//        entityList.add(discoveryEntity2);
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, R.layout.layout_recomm_dis_view, null, false);
        binding.setVariable(com.wwwzh.himalayafm.BR.discovery, discoveryEntity);
        ViewDataBinding binding2 = DataBindingUtil.inflate(inflater, R.layout.layout_recomm_dis_view, null, false);
        binding2.setVariable(com.wwwzh.himalayafm.BR.discovery, discoveryEntity2);
        views.add(binding.getRoot());
        views.add(binding2.getRoot());
//        Log.d("1620",entityList.get(0).getList().get(0).getTitle()+" first");
//        Log.d("1620",entityList.get(1).getList().get(0).getTitle()+" second");
        RecommDisAdapter adapter = new RecommDisAdapter(views);
        holder.disViewPager.setAdapter(adapter);
        holder.disPointLayout.getChildAt(0).setSelected(true);
        holder.disViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < holder.disPointLayout.getChildCount(); i++) {
                    holder.disPointLayout.getChildAt(i).setSelected(position == i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void adAutoCycle(final BottomAdViewHolder holder) {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.arg1 != 0) {
                    holder.adViewPager.setCurrentItem(msg.arg1);
                } else {
                    holder.adViewPager.setCurrentItem(msg.arg1, false);
                }
            }
        };
        if (timer2 != null) {
            timer2.cancel();
            timer2 = null;
        }
        timer2 = new Timer();
        timer2.schedule(new TimerTask() {
            @Override
            public void run() {
//                Log.d("1620","timer2 is running");
                Message msg = Message.obtain();
                if (adCurPosition == adList.size() - 1) {
                    adCurPosition = -1;
                }
                msg.arg1 = adCurPosition + 1;
                handler.sendMessage(msg);
            }
        }, 0, 5 * 1000);


    }

    //初始化viewPager
    private void initViewPager(final HeaderViewHolder holder) {
        if (isFirst == true) {
            mlist.addAll(entityOne.getFocusImages().getList());
            isFirst = false;
            Log.d("1620", mlist.get(0).getPic());
            final FocusImageAdapter adapter = new FocusImageAdapter(mlist, holder.viewPager.getContext());
            holder.viewPager.setAdapter(adapter);
            for (int i = 0; i < mlist.size(); i++) {
                ImageView pointImg = new ImageView(holder.pointLayout.getContext());
                pointImg.setImageResource(R.drawable.category_selector);
                pointImg.setPadding(10, 0, 10, 0);
                holder.pointLayout.addView(pointImg);
            }
            holder.pointLayout.getChildAt(0).setSelected(true);
            holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    curPosition = position;
                    for (int i = 0; i < holder.pointLayout.getChildCount(); i++) {
                        holder.pointLayout.getChildAt(i).setSelected(position == i);
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            autoCycle(holder);
        }

    }

    //自动循环
    private void autoCycle(final HeaderViewHolder holder) {

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.arg1 != 0) {
                    holder.viewPager.setCurrentItem(msg.arg1);
                } else {
                    holder.viewPager.setCurrentItem(msg.arg1, false);
                }
            }
        };
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
//                Log.d("1620","timer is running");
                Message msg = Message.obtain();
                if (curPosition == mlist.size() - 1) {
                    curPosition = -1;
                }
                msg.arg1 = curPosition + 1;
                handler.sendMessage(msg);
            }
        }, 0, 5 * 1000);

    }


    //判断item类型
    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return ITEM_TYPE_HEADER;
        } else if (position == 1) {
            return ITEM_TYPE_DISCOVERY;
        } else if (position == 2) {
            return ITEM_TYPE_GUESS;
        } else if (position == 4) {
            return ITEM_TYPE_SPECIAL;
        } else if (position == lists.size() + 5) {
            return ITEM_TYPE_BOTTOMAD;
        } else {
            return ITEM_TYPE_CONTENT;
        }
    }

    @Override
    public int getItemCount() {
        return lists.size() + 6;
    }


    //当推荐界面销毁时
    @Override
    public void onRecommDestory() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        } else if (timer2 != null) {
            timer2.cancel();
            timer2 = null;
        }
    }

//    public boolean isHeadView(int position){
//        if (position==0){
//            return true;
//        }
//        return false;
//    }

    //内容条目viewHolder
    public static class ContentViewHolder extends RecyclerView.ViewHolder {
        private ViewDataBinding binding;
        private ImageView image1;
        private ImageView image2;
        private ImageView image3;

        public ContentViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
            image1 = (ImageView) binding.getRoot().findViewById(R.id.item_imageOne);
            image2 = (ImageView) binding.getRoot().findViewById(R.id.item_imageTwo);
            image3 = (ImageView) binding.getRoot().findViewById(R.id.item_imageThree);
        }
    }

    //推荐界面discovery 的viewHolder
    public static class DiscoveryViewHolder extends RecyclerView.ViewHolder {
        private ViewPager disViewPager;
        private LinearLayout disPointLayout;

        public DiscoveryViewHolder(View itemView) {
            super(itemView);
            this.disViewPager = (ViewPager) itemView.findViewById(R.id.recomm_dis_viewpager);
            this.disPointLayout = (LinearLayout) itemView.findViewById(R.id.recomm_dis_pointLayout);
        }
    }

    //精品听单
    public static class SpecialViewHolder extends RecyclerView.ViewHolder {

        ViewDataBinding specialBinding;
        LinearLayout specialLayout;
        public SpecialViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.specialBinding = binding;
            this.specialLayout = (LinearLayout) binding.getRoot().findViewById(R.id.special_Layout);
        }
    }


    //头视图的viewHolder
    public static class HeaderViewHolder extends RecyclerView.ViewHolder {
        private ViewPager viewPager;
        private LinearLayout pointLayout;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            this.viewPager = (ViewPager) itemView.findViewById(R.id.recomm_viewPager);
            this.pointLayout = (LinearLayout) itemView.findViewById(R.id.pointLayout);
            Log.d("1620", "headviewholder");
        }
    }

    public static class BottomAdViewHolder extends RecyclerView.ViewHolder {

        private ViewPager adViewPager;

        public BottomAdViewHolder(View itemView) {
            super(itemView);
            this.adViewPager = (ViewPager) itemView.findViewById(R.id.bottomAdViewPager);
        }
    }

    //猜你喜欢viewHolder
    public static class GuessViewHolder extends RecyclerView.ViewHolder {
        private RecyclerView gridView;

        public GuessViewHolder(View itemView) {
            super(itemView);
            this.gridView = (RecyclerView) itemView.findViewById(R.id.recomm_guess_recycler);
        }
    }


    public class ClickListener implements View.OnClickListener {
        private String id;

        public ClickListener(String id) {
            this.id = id;
        }

        @Override
        public void onClick(View v) {
            if (mlistener != null) {
                mlistener.onImageClick(id);
            }
        }
    }

    public static void setOnImageClickListener(OnImageClickListener listener) {
        mlistener = listener;
    }

}
